package net.oschina.dajiangnan.wx.process.msg;

import java.io.InputStream;

import javax.servlet.http.HttpServletRequest;

import net.oschina.dajiangnan.util.XStreamHelper;
import org.apache.commons.io.IOUtils;

import net.oschina.dajiangnan.wx.process.mp.tools.SignatureValid;
import net.oschina.dajiangnan.wx.process.msg.xmlbean.XmlBean;


public class DisPatcher {
    
    public String disPatcher(HttpServletRequest req) throws Exception{
        
        String signature = req.getParameter("signature");
        String timestamp = req.getParameter("timestamp");
        String nonce = req.getParameter("nonce");
        
        
        XmlBean respXmlBean = null;
        
        if(SignatureValid.valid(signature,timestamp,nonce)){
            InputStream reqBody = req.getInputStream();
            String xmlStr = IOUtils.toString(reqBody,"UTF-8");
            
            if(xmlStr.indexOf("<MsgType><![CDATA[text]]></MsgType>") != -1){
                respXmlBean = new Text().process(xmlStr);
            }
            if(xmlStr.indexOf("<MsgType><![CDATA[event]]></MsgType>") != -1){
                respXmlBean = new EventDisPatcher().process(xmlStr);
            }
        }
        
        return respXmlBean == null ? "": XStreamHelper.toXml(respXmlBean);
    }
}
